var util = require('../../utils/util.js');

var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
var user_id;
var page = 1;
var orders = [];
var type = 1;

function getOrderList (that) {
  console.log(parseInt(that.data.activeIndex) + 1);
  that.setData({
    inputVal: ''
  });
  getApp().sp();
  user_id = wx.getStorageSync('user_id');
  wx.request({
    url: getApp().globalData.apiurl + 'getOrderList',
    method: 'POST',
    data: {
      "user_id": user_id,
      "page": page,
      "type": type,
      "like": that.data.inputVal,
      "pagesize": 20
    },
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
    success: function (res) {
      console.log(res.data);
      getApp().hp();
      wx.stopPullDownRefresh();
      if (res.data.isSuccess == 1) {
        for (var i = 0; i < res.data.data.length; i++) {
          orders.push(res.data.data[i]);
        }
        if (res.data.data.length < 20) {
          that.setData({
            more: 0
          });
        }
        that.setData({
          orders: orders
        })
        page++;
      } else {
        that.setData({
          more: 0
        })
        if (page == 1) {
          that.setData({
            orders: [],
            more: 0
          })
        } else {
          that.setData({
            more: 0
          })
        }
      }

    }
  })
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ["重箱出场", "空箱入场", "空箱出场", "重箱入场"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    more: 1,
    need_pad: 0,
    inputShowed: false,
    inputVal: ""
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
    orders = [];
    type = 1;
    var that = this;
    page = 1;
    getOrderList(that);
    that.setData({
      need_pad: wx.getStorageSync('need_pad')
    })
  },
  tabClick: function (e) {
    if (e.currentTarget.id == 0) {
      type = 1;
    } else if (e.currentTarget.id == 1) {
      type = 2
    } else if (e.currentTarget.id == 2) {
      type = 3
    } else if (e.currentTarget.id == 3) {
      type = 4
    }
    this.onPullDownRefresh();
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },

  onShow: function () {
    //this.onPullDownRefresh();
    // this.setData({
    //   sliderOffset: e.currentTarget.offsetLeft,
    //   activeIndex: e.currentTarget.id
    // });
  },

  scaner_pound: function (e) {

    var that = this;
    var index = e.currentTarget.dataset.index;
    // console.log(orders);
    // return;
    var order_no = e.currentTarget.dataset.order_no;
    var user_id = wx.getStorageSync('user_id');
    wx.scanCode({
      success: function (res) {
        var arr = res.result.split(",");
        wx.request({
          url: getApp().globalData.apiurl + 'uploadPound',
          method: 'POST',
          data: {
            "user_id": user_id,
            "order_no": order_no,
            "gross_weight_time": arr[5],
            "gross_weight": arr[6],
            "tare_weight_time": arr[7],
            "tare_weight": arr[8],
            "net_weight": arr[9],
            "pound_no": arr[10]
          },
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success: function (res) {
            getApp().hp();
            console.log(res.data);
            if (res.data.isSuccess == 1) {

              orders[index].upload_pound_time = util.getTime(new Date());
              that.setData({
                orders: orders
              })
              getApp().alert("磅单上传成功！");
            } else {
              getApp().alert(res.data.msg);
            }
          }
        })
      }
    })

  },


  open_ewm: function (e) {

    wx.navigateTo({
      url: '/pages/qrcode/qrcode?order_no=' + e.currentTarget.dataset.order_no + '&container_no=' + e.currentTarget.dataset.container_no
    })

    // var url = "http://pan.baidu.com/share/qrcode?w=600&h=600&url="+e.currentTarget.dataset.order_no;
    // wx.previewImage({
    //   current: url, // 当前显示图片的http链接
    //   urls: [url] // 需要预览的图片http链接列表
    // })

  },
  delete_empty_order: function (e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var that = this;
    wx.showModal({
      title: '警告！',
      content: "删除该返箱后，信息将无法恢复！",
      cancelText: "我再想想",
      confirmText: "确定删除",
      confirmColor: "#c71d23",
      success: function (res) {
        if (res.confirm) {
          getApp().sp();
          wx.request({
            url: getApp().globalData.apiurl + 'unbindEmptyContainer',
            method: 'POST',
            data: {
              "user_id": user_id,
              "id": id
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              getApp().hp();
              console.log(res.data);
              if (res.data.isSuccess == 1) {
                orders.splice(index, 1);
                that.setData({
                  orders: orders
                })
                getApp().alert("删除成功！");
              } else {
                getApp().alert(res.data.res);
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  delete_order: function (e) {
    var that = this;
    var order_no = e.currentTarget.dataset.order_no;
    var index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '警告！',
      content: "删除该单后，箱号会回到箱号池中，你录入的榜单信息将无法恢复！",
      cancelText: "我再想想",
      confirmText: "确定删除",
      confirmColor: "#c71d23",
      success: function (res) {
        if (res.confirm) {
          getApp().sp();
          wx.request({
            url: getApp().globalData.apiurl + 'unbindHeavyContainer',
            method: 'POST',
            data: {
              "user_id": user_id,
              "order_no": order_no
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              getApp().hp();
              console.log(res.data);
              if (res.data.isSuccess == 1) {
                orders.splice(index, 1);
                that.setData({
                  orders: orders
                })
                getApp().alert("删除成功！");
              } else {
                getApp().alert(res.data.res);
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },

  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    page = 1;
    orders = [];
    var that = this;
    //getOrderList(that);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    //getOrderList(that);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // showInput: function () {
  //     this.setData({
  //         inputShowed: true
  //     });
  // },
  // hideInput: function () {
  //     this.setData({
  //         inputVal: "",
  //         inputShowed: false
  //     });
  // },
  // clearInput: function () {
  //     this.setData({
  //         inputVal: ""
  //     });
  // },
  // inputTyping: function (e) {
  //     this.setData({
  //         inputVal: e.detail.value
  //     });
  // },

  /***** 搜索一系列 start ****/
  /**
   * TODO(搜索框输入ing)
   * @param
   * @auther zhangQ
   * @date 2018/1/25 17:22
   **/
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    })
    if (!(e.detail.value + '')) {
      this.backDisplayDriverList()
      return
    }
    let orderList = this.data.orders
    console.log(orderList);
    for (var i = 0; i < orderList.length; i++) {
      if ((orderList[i].container_no_head + ' ' + orderList[i].container_no_body).indexOf(e.detail.value) >= 0 || (orderList[i].container_no && orderList[i].container_no.indexOf(e.detail.value) >= 0)) {
        orderList[i].isShow = !true
      } else {
        orderList[i].isShow = !false
      }
    }
    this.setData({
      orders: orderList
    })
  },
  /**
   * TODO(搜索框被点击)
   * @param
   * @auther zhangQ
   * @date 2018/1/25 17:22
   **/
  searchInput: function () {
    this.setData({
      inputShowed: true
    })
  },
  hideInput: function () {
    this.setData({
      inputShowed: false
    })
    this.clearInput()
    // 回显old driverList
    this.backDisplayDriverList()

  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    })
    this.backDisplayDriverList()
  },
  /**
   * TODO(回显)
   * @param
   * @auther zhangQ
   * @date 2018/1/25 17:47
   **/
  backDisplayDriverList () {
    let orderList = this.data.orders
    for (var i = 0; i < orderList.length; i++) {
      orderList[i].isShow = !true
    }
    this.setData({
      orders: orderList
    })
  },
  /***** 搜索一系列 end ****/
  /**
   * TODO(补充媒体信息)
   * @auther zhangQ
   * @date 2018/4/16 12:46
   */
  addMedia (e) {
    // wx.showModal({
    //   title: '警告！',
    //   content: "删除该单后，箱号会回到箱号池中，你录入的榜单信息将无法恢复！",
    //   cancelText: "我再想想",
    //   confirmText: "确定删除",
    //   confirmColor: "#c71d23",
    //   success: function (res) {
    //     if (res.confirm) {
    //       getApp().sp();
    //       wx.request({
    //         url: getApp().globalData.apiurl + 'unbindHeavyContainer',
    //         method: 'POST',
    //         data: {
    //           "user_id": user_id,
    //           "order_no": order_no
    //         },
    //         header: {
    //           "content-type": "application/x-www-form-urlencoded"
    //         },
    //         success: function (res) {
    //           getApp().hp();
    //           console.log(res.data);
    //           if (res.data.isSuccess == 1) {
    //             orders.splice(index, 1);
    //             that.setData({
    //               orders: orders
    //             })
    //             getApp().alert("删除成功！");
    //           } else {
    //             getApp().alert(res.data.res);
    //           }
    //         }
    //       })
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
    var that = this
    var order_no = e.currentTarget.dataset.order_no
    var index = e.currentTarget.dataset.index
    var activeIndex = this.data.activeIndex
    var heavy_or_empty = ''
    var order = orders[index]
    var in_or_out = ''
    if (activeIndex == 0) {
      heavy_or_empty = 1
      in_or_out = 1
    } else if (activeIndex == 1) {
      heavy_or_empty = 0
      in_or_out = 2
    } else if (activeIndex == 2) {
      heavy_or_empty = 0
      in_or_out = 1
    } else if (activeIndex == 3) {
      heavy_or_empty = 1
      in_or_out = 2
    } else {
      return
    }
    wx.navigateTo({
      url: '/pages/bind_other/bind_other?heavy_or_empty=' + heavy_or_empty + '&in_or_out=' + in_or_out + '&isEdit=true&order=' + JSON.stringify(order)
    })
    // tabs: ["重箱出场", "空箱入场", "空箱出场", "重箱入场"],
  }
})